package com.zenithsun.common.security.url;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;


/**
 * 请求过滤，对请求参数进行过滤、验证、转义等 XSS,CRLF漏洞
 * 
 * @author Jiang
 *
 */
public class URLHttpServletRequestWrapper extends HttpServletRequestWrapper {
	HttpServletRequest orgRequest = null;

	public URLHttpServletRequestWrapper(HttpServletRequest request) {

		super(request);
		orgRequest = request;
	}

	/**
	 * 过滤URL参数
	 */
	@Override
	public String getParameter(String name) {
		// http://localhost:8080/JS_SIS/theme/cerulean?url=http://www.baidu.com
		String value = super.getParameter(name);
		//获取URL参数的白名单
		String urlParams = "url,href,";
		/*
		 * if(name.toLowerCase().equals("url")){ String referer =
		 * getOrgRequest(orgRequest).getScheme()+"//:"+
		 * getOrgRequest(orgRequest).getServerName();
		 * if(!value.toLowerCase().startsWith(referer.toLowerCase())){ return
		 * ""; } }
		 */
		if (urlParams.indexOf(name.toLowerCase() + ",") > 0) {
			String referer = getOrgRequest(orgRequest).getScheme() + "//:" + getOrgRequest(orgRequest).getServerName();
			if (!value.toLowerCase().startsWith(referer.toLowerCase())) {
				return "/";
			}
		}
		return value;
	}

	/**
	 * 获取最原始的request
	 * 
	 * @return
	 */
	public HttpServletRequest getOrgRequest() {
		return orgRequest;
	}

	/**
	 * 获取最原始的request的静态方法
	 * 
	 * @return
	 */
	public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
		if (req instanceof URLHttpServletRequestWrapper) {
			return ((URLHttpServletRequestWrapper) req).getOrgRequest();
		}

		return req;
	}
}